<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Exceptions\AppException;
use App\Exports\TaskExport;
use App\Exports\TaskLoadExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\dispatch\TaskRequest;
use App\Imports\TaskImport;
use App\Models\base\WarehouseModel;
use App\Models\CustomerModel;
use App\Models\DictionaryModel;
use App\Models\dispatch\CarModel;
use App\Models\dispatch\ExceptionModel;
use App\Models\dispatch\UnloadModel;
use App\Models\DispatchCostModel;
use App\Models\DispatchLoadListModel;
use App\Models\DispatchTaskDriverModel;
use App\Models\DispatchTaskLoadModel;
use App\Models\DispatchTaskLocationModel;
use App\Models\DispatchTaskModel;
use App\Models\DispatchTaskRecordModel;
use App\Models\DispatchTaskUnloadModel;
use App\Models\OrderModel;
use App\Models\OrderNodeLogModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class Task extends Controller
{
    use TaskRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_sn = $request->input('order_sn', '');
        $status = $request->input('status', '');
        $load_form = $request->input('carView', '');
        $agent_id = $request->input('agent_id', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');
        $type = $request->input('type', '');
        $car_number = $request->input('car_id', '');

        $query = DispatchTaskModel::query()
            ->with(['create_admin', 'agent', 'feng', 'driver', 'hk_driver', 'car','load_list', 'type', 'unloads', 'loads', 'exception']);

        if($order_sn){
            $order_id = OrderModel::where('sn', 'like', "%$order_sn%")->pluck('id');
            $order_id = $order_id->toArray() ?? [];
            $task_ids = DispatchLoadListModel::whereIn('order_id', $order_id)->pluck('dispatch_task_id')->toArray();
            $query->whereIn('id', $task_ids);
        }

        if($status){
            $query->where('status', $status);
        }

        if($type) {
            $query->where('type', $type);
        }

        if($load_form){
            $query->where('load_form', $load_form);
        }

        if($agent_id){
            $query->where('agent_id', $agent_id);
        }

        if($car_number){
            $car_id = CarModel::where('car_number', 'like', "%$car_number%")->pluck('id');
            $query->whereIn('car_id', $car_id);
        }

        if($create_start && $create_end){
            $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            //车牌号
            $car_number = $item->car->car_number ?? '';

            //装车地
            $load_warehouse_ids = $item->loads->map(function ($item2) {
                return $item2->warehouse_id;
            });

            $load_warehouse_name = WarehouseModel::whereIn('id', $load_warehouse_ids)->pluck('name')->toArray();

            //卸货地
            $unload_warehouse_ids = $item->unloads->map(function ($item2) {
                return $item2->warehouse_id;
            });

            $unload_warehouse_name = UnloadModel::whereIn('id', $unload_warehouse_ids)->pluck('name')->toArray();

            $driver_info = $hk_driver_info = [];
            if($item->driver){
                $driver_info = [
                    'name' => $item->driver->name ?? '',
                    'mobile' => $item->driver->mobile ?? '',
                    'hk_mobile' => $item->driver->mobile ?? '',
                    'id_card' => $item->driver->id_number ?? '',
                    'card_number' => $item->driver->card_number ?? '',
                ];
            }

            if($item->hk_driver){
                $hk_driver_info = [
                    'name' => $item->hk_driver->name ?? '',
                    'mobile' => $item->hk_driver->mobile ?? '',
                    'hk_mobile' => $item->hk_driver->mobile ?? '',
                    'id_card' => $item->hk_driver->id_number ?? '',
                    'card_number' => $item->hk_driver->card_number?? '',
                ];
            }

            if($item->exception){
                $exceptions = $item->exception->map(function ($item2) {
                    return $item2->name;
                })->toArray();
                $exception = implode(',', $exceptions);
            }else{
                $exception = '';
            }
            
            return [
                'id' => $item->id,
                'load_date' => $item->load_date,
                'car_type' => $item->type->name ?? '',
                'car_agent' => $item->car->agent->name ?? '',
                'car_number' => $car_number,
                'driver_info' => $driver_info,
                'hk_driver_info' => $hk_driver_info,
                'load_warehouse' => $load_warehouse_name,
                'unload_warehouse_name' => $unload_warehouse_name,
                'feng_name' => $item->feng->name ?? '',
                'agent_name' => $item->agent->name ?? '',
                'big_pkgs' => $item->load_list->sum('big_pkgs'), //大包数量
                'weight' => $item->load_list->sum('weight'), //
                'exception' => $exception,
                'status' => $item->status,
                'status_text' => DispatchTaskModel::STATUS_MAPS[$item->status] ?? '',
                'load_form' => DispatchTaskModel::LOAD_MAPS[$item->load_form] ?? '',
                'created_at' => $item->created_at->toDateTimeString(),
            ];
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {

            $car_info = CarModel::find($params['car_id']);
            if(!$car_info){
                return $this->error('车辆不存在');
            }

            $task = new DispatchTaskModel();
            $task->load_date  = $params['load_date'];
            $task->type_id = intval($params['type_id'] ?? 0);
            $task->car_id = intval($params['car_id'] ?? 0);
            $task->agent_id = intval($params['agent_id'] ?? 0);
            $task->feng_id = $params['feng_id'] ?? 0;
//            $task->driver_id = $car_info->driver_id ?? 0;
//            $task->hk_driver_id = $car_info->hk_driver_id ?? 0;
            $task->driver_id = intval($params['driver_id'] ?? 0);
            $task->hk_driver_id = intval($params['hk_driver_id'] ?? 0);
            $task->created_admin_id = $auth->id;
            $task->save();

            foreach($params['load_warehouse_ids'] as $load_warehouse_id) {
                DispatchTaskLoadModel::create([
                    'dispatch_task_id' => $task->id,
                    'warehouse_id' => $load_warehouse_id,
                ]);
            }

            foreach($params['unload_warehouse_ids'] as $unload_warehouse_id) {
                DispatchTaskUnloadModel::create([
                    'dispatch_task_id' => $task->id,
                    'warehouse_id' => $unload_warehouse_id,
                ]);
            }

            if(isset($params['driver_id'])){
                $task_driver = new DispatchTaskDriverModel();
                $task_driver->task_id = $task->id;
                $task_driver->driver_id = intval($params['driver_id']);
                $task_driver->type = 2;
                $task_driver->task_type = 1;
                $task_driver->status_type = 1;
                $task_driver->is_start = 1;
                $task_driver->save();
            }

            if(isset($params['hk_driver_id'])){
                $task_driver = new DispatchTaskDriverModel();
                $task_driver->task_id = $task->id;
                $task_driver->driver_id = intval($params['hk_driver_id']);
                $task_driver->type = 1;
                $task_driver->task_type = isset($params['driver_id']) ? 1 : 2;
                $task_driver->status_type = isset($params['driver_id']) ? 2 : 3;
                $task_driver->is_start = isset($params['driver_id']) ? 0 : 1;
                $task_driver->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function update(Request $request){
        $auth = $request->get('auth');
        $id = $request->input('id',  '');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $task = DispatchTaskModel::find($id);
        if(!$task){
            return $this->error('任务不存在');
        }

        DB::beginTransaction();
        try {

            $car_info = CarModel::find($params['car_id']);
            if(!$car_info){
                return $this->error('车辆不存在');
            }

            $task->load_date  = $params['load_date'];
            $task->type_id = intval($params['type_id'] ?? 0);
            $task->car_id = intval($params['car_id'] ?? 0);
            $task->agent_id = intval($params['agent_id'] ?? 0);
            $task->feng_id = $params['feng_id'] ?? 0;
//            $task->driver_id = $car_info->driver_id ?? 0;
//            $task->hk_driver_id = $car_info->hk_driver_id ?? 0;
            $task->driver_id = intval($params['driver_id'] ?? 0);
            $task->hk_driver_id = intval($params['hk_driver_id'] ?? 0);
            $task->created_admin_id = $auth->id;
            $task->save();

//            DispatchTaskLoadModel::where('dispatch_task_id', $task->id)->delete();
            foreach($params['load_warehouse_ids'] as $load_warehouse_id) {
                $find_load = DispatchTaskLoadModel::where('dispatch_task_id', $task->id)->where('warehouse_id', $load_warehouse_id)->first();
                if(!$find_load){
                    DispatchTaskLoadModel::create([
                        'dispatch_task_id' => $task->id,
                        'warehouse_id' => $load_warehouse_id,
                    ]);
                }
            }
            DispatchTaskLoadModel::where('dispatch_task_id', $task->id)->whereNotIn('warehouse_id', $params['load_warehouse_ids'])->delete();

//            DispatchTaskUnloadModel::where('dispatch_task_id', $task->id)->delete();
            foreach($params['unload_warehouse_ids'] as $unload_warehouse_id) {
                $find_unload = DispatchTaskUnloadModel::where('dispatch_task_id', $task->id)->where('warehouse_id', $unload_warehouse_id)->first();
                if(!$find_unload){
                    DispatchTaskUnloadModel::create([
                        'dispatch_task_id' => $task->id,
                        'warehouse_id' => $unload_warehouse_id,
                    ]);
                }
            }
            DispatchTaskUnloadModel::where('dispatch_task_id', $task->id)->whereNotIn('warehouse_id', $params['unload_warehouse_ids'])->delete();


            if(isset($params['driver_id'])){
                $task_driver = DispatchTaskDriverModel::where('task_id', $task->id)->where('driver_id', $params['driver_id'])->first();
                if(!$task_driver){
                    $task_driver = new DispatchTaskDriverModel();
                    $task_driver->task_id = $task->id;
                    $task_driver->driver_id = intval($params['driver_id']);
                    $task_driver->type = 2;
                    $task_driver->task_type = 1;
                    $task_driver->status_type = 1;
                    $task_driver->is_start = 1;
                    $task_driver->save();
                }


            }

            if($params['hk_driver_id']){
                $task_driver = DispatchTaskDriverModel::where('task_id', $task->id)->where('driver_id', $params['hk_driver_id'])->first();
                if(!$task_driver){
                    $task_driver = new DispatchTaskDriverModel();
                    $task_driver->task_id = $task->id;
                    $task_driver->driver_id = intval($params['hk_driver_id']);
                    $task_driver->type = 1;
                    $task_driver->task_type = isset($params['driver_id']) ? 1 : 2;
                    $task_driver->status_type = isset($params['driver_id']) ? 2 : 3;
                    $task_driver->is_start = isset($params['driver_id']) ? 0 : 1;
                    $task_driver->save();
                }

            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function delete(int $id){
        $task = DispatchTaskModel::find($id);
        if(!$task){
            return $this->error('任务不存在');
        }
        if($task->status != DispatchTaskModel::STATUS_WAIT){ 
            return $this->error('任务已开始，无法删除');
        }
        $task->delete();
        return $this->success();
    }

    public function detail(int $id){
        $task = DispatchTaskModel::with(['unloads', 'loads'])->find($id);
        if(!$task){
            return $this->error('任务不存在');
        }

        $return = [
            'id' => $task->id,
            'load_date' => $task->load_date,
            'type_id' => $task->type_id,
            'car_id' => $task->car_id,
            'agent_id' => $task->agent_id,
            'feng_id' => $task->feng_id,
            'driver_id' => $task->driver_id,
            'hk_driver_id' => $task->hk_driver_id,
            'load_warehouse_ids' => $task->loads?->pluck('warehouse_id'),
            'unload_warehouse_ids' => $task->unloads?->pluck('warehouse_id'),
        ];

        return $this->success($return);
    }

    //装车表
    public function load_list(int $id){
        $task = DispatchTaskModel::with( [
            'load_list' => function($query){
                $query->with([
                    'order' => function($query){
                        $query->with([
                            'customer' => function($query){
                                $query->with(['customer_type']);
                            },
                            'des_country'
                        ]);
                    }
                ]);
            }
        ])->find($id);
        if(!$task){
            return $this->error('任务不存在');
        }

        $driver = $task->driver;
        $hk_driver = $task->hk_driver;

        $driver_info = $hk_driver_info = '';
        if($driver){
            $type = '大陆司机';
            $driver_info .= $type . '：' . $driver->name;
            $driver_info .= ' 电话：' . $driver->mobile;
            $driver_info .= ' 身份证号：' . $driver->id_number;
        }

        if($hk_driver){
            $type = '港车司机';
            $hk_driver_info .= $type . '：' . $hk_driver->name;
            $hk_driver_info .= ' 卡号：' . $hk_driver->card_number;
            $hk_driver_info .= ' 电话：' . $hk_driver->mobile;

        }

        $car_type = DictionaryModel::find($task->car->type_id)->name ?? '';

        //装车地
        $load_warehouse_ids = $task->loads->map(function ($item2) {
            return $item2->warehouse_id;
        });

        $load_warehouse_name = WarehouseModel::whereIn('id', $load_warehouse_ids)->pluck('name')->toArray();

        //卸货地
        $unload_warehouse_ids = $task->unloads->map(function ($item2) {
            return $item2->warehouse_id;
        });

        $unload_warehouse_name = UnloadModel::whereIn('id', $unload_warehouse_ids)->pluck('name')->toArray();

        $nerv = [
            'car_number' => $task->car->car_number ?? '',
            'car_type' => $car_type,
            'driver' => $driver_info,
            'hk_driver' => $hk_driver_info,
            'feng' => $task->feng->name ?? '',
            'big_pkgs' => $task->load_list->sum('big_pkgs'),
            'weight' => $task->load_list->sum('weight'),
            'load_warehouse' => $load_warehouse_name,
            'unload_warehouse' => $unload_warehouse_name,
        ];

        $res = [];
        foreach($task->load_list as $item){
            //装货进度
            $order_big_pkgs = $item->order->big_pkgs ?? 0;
//            $order_load_surplus = $item->order->load_pkgs_surplus ?? 0;
            $progress =  $item->order->load_pkgs ?? 0 . "/{$order_big_pkgs}";

            //包装
            $packages_name = DictionaryModel::whereIn('id', explode(',', $item->packages))
                    ->pluck('name')->implode('+');

            $res[] = [
                'id' => $item->id,
                'customer_name' => $item->order->customer->name ?? '',
                'custmoer_sn' => $item->order->customer->sn ?? '',
                'customer_type' => $item->order->customer->customer_type->name ?? '',
                'order_ns' => $item->order->sn ?? '',
                'storage_time' => $item->order->storage_time ?? '',  //入库日期
                'pre_out_date' => $item->order->pre_out_date ?? '',
                'des_country' => $item->order->airport->country_name ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->order->goods_attr ?? ''] ?? '',
                'load_nums' => $item->big_pkgs,  //装载大包件数
                'weight' => $item->weight,
                'progress' =>  $progress,
                'packages_name' => $packages_name,
                'order_id' => $item->order_id,
            ];
        }

        return $this->success([
            'list' => $res,
            'nerv' => $nerv
        ]);

    }

    //添加装车表
    public function load_add(Request $request, int $id) {
        $params = $request->all();
        $validator = Validator::make($params, [
            'order_id' => 'required',
            'nums' => 'required|numeric',
            'weight' => 'required|numeric',
        ], [
            'order_id.required' => '请选择订单',
            'nums.required' => '请输入数量',
            'weight.required' => '请输入重量',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $task = DispatchTaskModel::find($id);
        if(!$task){
            return $this->error('任务不存在');
        }

        $order = OrderModel::find($params['order_id']);
        if(!$order){
            return $this->error('入仓单不存在');
        }

        if($order->big_pkgs < $params['nums']) {
             return $this->error('入仓单大包数量不足');
        }

        if($order->storage_weight < $params['weight']) {
            return $this->error('入仓单入库重量数量不足');
        }

        if($order->status < OrderModel::STATUS_STORAGE){
            return $this->error('入仓单未入库');
        }

        try{
            DB::transaction(function () use ($task, $order, $params, $request) {

                $load_list = new DispatchLoadListModel();
                $load_list->dispatch_task_id = $task->id;
                $load_list->big_pkgs = $params['nums'];
                $load_list->weight = $params['weight'];

                //子单
                if($params['nums'] < $order->big_pkgs){
                    $new_order = $order->replicate();
                    $order->children_nums += 1;

                    $new_order->sn = $order->sn . '_' . DispatchLoadListModel::CHILDREN_SN[$order->children_nums];
                    $new_order->is_child = 1;
                    $new_order->father_order_id = $order->id;
                    $new_order->status = OrderModel::STATUS_OUTSTOCK;
                    $new_order->car_number = $task->car->car_number ?? '';
                    $new_order->load_pkgs = $params['nums'];
                    $new_order->load_weight = $params['weight'];
                    $new_order->big_pkgs = $params['nums'];
                    $new_order->storage_weight = $params['weight'];
                    $new_order->out_time = date('Y-m-d H:i:s');
                    $new_order->is_load = 2;
                    $new_order->save();

                    $this->node_log($request, $new_order->id, '出库', date('Y-m-d H:i:s'));

                    $load_list->order_id = $new_order->id;
                }else{
                    $load_list->order_id = $order->id;

                    $this->node_log($request, $params['order_id'], '出库', date('Y-m-d H:i:s'));
                }

                $load_list->save();

                $load_pkgs = $order->load_pkgs + $params['nums'];
                $load_weight = $order->load_weight + $params['weight'];
                $order->load_pkgs = $load_pkgs;
                $order->load_weight = $load_weight;
                $order->status = OrderModel::STATUS_OUTSTOCK;
                $order->outstock_time = date('Y-m-d H:i:s');
                $order->out_time = date('Y-m-d H:i:s');
                $order->car_number = $task->car->car_number ?? '';
                if($load_pkgs >= $order->big_pkgs){
                    $order->is_load  = 2;
                }else{
                    $order->is_load  = 1;
                }
                $order->save();

                $task->load_form = 2;
//                $task->save();

                //出库
                $task->out_time = date('Y-m-d H:i:s');
                $task->node_status = DispatchTaskModel::NODE_STATUS_OUT;
                $task->save();


            });
        } catch(\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //编辑装车
    public function load_update(Request $request, $id) {
        $params = $request->all();
        $validator = Validator::make($params, [
            'nums' => 'required|numeric',
            'weight' => 'required|numeric',
        ], [
            'nums.required' => '请输入数量',
            'weight.required' => '请输入重量',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $load = DispatchLoadListModel::find($id);
        if(!$load){
            return $this->error('装车记录不存在');
        }

        $task = DispatchTaskModel::find($load->dispatch_task_id);
        if(!$task){
            return $this->error('任务不存在或已删除');
        }

        $order = OrderModel::find($load->order_id);
        if(!$order){
            return $this->error('入仓单不存在或被删除');
        }

//        if(($order->load_pkgs_surplus + $load->big_pkgs) < $params['nums'] ) {
//            return $this->error('入仓单大包数量不足');
//        }
//
//        if(($order->surplus_weight + $load->weight) < $params['weight']) {
//            return $this->error('入仓单重量不足');
//        }

        try{
            DB::transaction(function () use ($task, $order, $params, $load) {
                $nums = $params['nums'] - $load->big_pkgs;
                $weight = $params['weight'] - $load->weight;
                $load_pkgs = $order->load_pkgs + $nums;
                $order->load_pkgs = $load_pkgs;
                $order->load_weight = DB::raw("load_weight + {$weight}");
                if($load_pkgs >= $order->big_pkgs){
                    $order->is_load  = 2;
                }else{
                    $order->is_load  = 1;
                }
                $order->save();

                $task->load_form = 2;
                $task->save();

                $load->big_pkgs = $params['nums'];
                $load->weight = $params['weight'];
                $load->save();
            });
        } catch(\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //可装车入仓单
    public function loadable(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);


        $query = (function() use ($request){
            $keyword = $request->input('keyword', '');
            $goods_attr = $request->input('goods_type', '');
            $des_country_id = $request->input('manifest_id', '');
            $clearance_mode = $request->input('custom_clear', '');
            $customer_type = $request->input('customer_type', '');
            $is_clearance = $request->input('clearance_delivery', '');
            $pre_start_time = $request->input('pre_star_time', '');
            $pre_end_time = $request->input('pre_end_time', '');
            $join_star_time = $request->input('join_star_time', '');
            $join_end_time = $request->input('join_end_time', '');

            $query = OrderModel::query()
                ->where('is_load', '<', 2)
//                ->where('load_pkgs_surplus', '>', 0)
//                ->where('surplus_weight', '>', 0)
                ->where('is_exception', 0)
                ->with([
                    'create_admin', 'take_order_addr', 'customer', 'split_order_addr', 'take_order'
                ])->withCount('split_order_addr');


            if($keyword) {
                $query->where(function($query) use ($keyword) {
                    $query->where('sn', $keyword)
                        ->orWhere(function($query) use ($keyword) {
                            $query->whereHas('customer', function($query) use ($keyword) {
                                $query->where('name', $keyword)->orWhere('sn', $keyword);
                            });
                        });
                });
            }

            if($goods_attr) {
                $query->where('goods_attr', $goods_attr);
            }

            if($des_country_id) {
                $query->where('des_country_id', $des_country_id);
            }

            if($clearance_mode) {
                $query->where('clearance_mode', $clearance_mode);
            }

            if($customer_type) {
                $query->whereIn('customer_id', function($query) use ($customer_type){
                    $query->select('id')
                        ->from((new CustomerModel())->getTable())
                        ->where('customer_type_id', $customer_type);
                });
            }

            if(is_numeric($is_clearance)) {
                $query->where('is_clearance', $is_clearance);
            }

            if($pre_start_time) {
                $query->where('pre_out_date', '>=', $pre_start_time);
            }

            if($pre_end_time) {
                $query->where('pre_out_date', '<=', $pre_end_time);
            }

            if($join_star_time) {
                $query->where('storage_time', '>=', $join_star_time);
            }

            if($join_end_time) {
                $query->where('storage_time', '<=', $join_end_time);
            }

            return $query;
        })();

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();


        $list = $items->map(function($item) {
            //装货进度
            // $order_big_pkgs = $item->big_pkgs ?? 0;
            // $order_load_surplus = $item->load_pkgs_surplus ?? 0;
            $progress =  $item->load_pkgs . "/{$item->big_pkgs}";

            //包装
            $packages_name = DictionaryModel::whereIn('id', explode(',', $item->packages))
                    ->pluck('name')->implode('+');

            //运输重量
            $weight = floatval($item->load_weight) . "/{$item->storage_weight}";

            $unload_warehouse = $item->take_order?->flight?->unload_warehouse?->name ?? '';

            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'custmoer_sn' => $item->customer->sn ?? '',
                'customer_type' => $item->customer->customer_type->name ?? '',
                'order_ns' => $item->sn ?? '',
                'storage_time' => $item->storage_time ?? '',  //入库日期
                'pre_out_date' => $item->pre_out_date ?? '',
                'des_country' => $item->airport->country_name ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr ?? ''] ?? '',
                'load_nums' => $item->big_pkgs,  //装载大包件数
                'weight' => $weight,
                'progress' =>  $progress,
                'packages_name' => $packages_name,
                'unload_warehouse' => $unload_warehouse,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    //运输成本
    public function costs(Request $request, int $id) {
        $task = DispatchTaskModel::with('costs')->find($id);
        if(!$task) {
            return $this->error('任务不存在');
        }

        $costs = $task->costs;


        $total = [];

        $list = $costs->map(function($cost)  use (&$total){
            $edit_form = [
                'subject_id' => $cost->subject_id,
                'amount' => $cost->amount,
                'currency_id' => $cost->currency_id,
                'remark' => $cost->remark
            ];

            $symbol = $cost->currency->symbol ?? '';
            $detail = [
                'subject_name' => $cost->subject->name ?? '',
                'currency_symbol' => $symbol,
                'amount' => $cost->amount,
                'remark' => $cost->remark
            ];
            
            if(isset($total[$cost->currency_id])) {
                $total[$symbol] += $cost->amount;
            } else {
                $total[$symbol] = $cost->amount;
            }

            return [
                'edit_form' => $edit_form,
                'detail' => $detail,
            ];
        });

        $total_text = '';
        foreach($total as $symbol => $amount) {
            $total_text .= "{$symbol}{$amount},";
        }

        //去掉结尾的逗号
        $total_text = rtrim($total_text, ', ');

        return $this->success(['list' => $list, 'total' => $total_text]);

    }

    //修改运输成本
    public function update_cost(Request $request, int $id) {
        $task = DispatchTaskModel::find($id);
        if (!$task) {
            return $this->error('任务不存在');
        }

        $params = $request->all();
        $check_res = self::cost_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        try{
            DB::transaction(function () use ($params, $task) {
                DispatchCostModel::where('dispatch_task_id', $task->id)->delete();

                foreach($params['costs'] as $cost) {
                    DispatchCostModel::create([
                        'dispatch_task_id' => $task->id,
                        'subject_id' => $cost['subject_id'],
                        'amount' => $cost['amount'],
                        'currency_id' => $cost['currency_id'],
                        'remark' => $cost['remark'] ?? ''
                    ]);
                }
            });
        } catch(\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //未配载入仓单
    public function unloading(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $customer_name = $request->input('customer_name', '');
        $order_sn = $request->input('order_sn', '');
        $goods_attr = $request->input('goods_attr', '');
        $des_country_id = $request->input('des_country_id', 0);
        $clearance_mode = $request->input('clearance_mode', '');
        $customer_type_id = $request->input('customer_type_id', '');
        $is_clearance = $request->input('is_clearance', '');
        $pre_out_date_start = $request->input('pre_out_date_start', '');
        $pre_out_date_end = $request->input('pre_out_date_end', '');

        $query = OrderModel::query()->with(['customer'])
            ->where('status', '>=', OrderModel::STATUS_CONFIRM)
            ->where('is_load', '<', 2);
//            ->where('load_pkgs_surplus', '>', 0)
//            ->where('surplus_weight', '>', 0);

        if($customer_name){
            $query->whereHas('customer', function($q) use ($customer_name) {
                $q->where('name', 'like', "%{$customer_name}%");
            });
        }

        if($order_sn){
            $query->where('sn', $order_sn);
        }

        if($goods_attr){
            $query->where('goods_attr', $goods_attr);
        }

        if($des_country_id){
            $query->where('destination', $des_country_id);
        }

        if($clearance_mode){
            $query->where('clearance_mode', $clearance_mode);
        }

        if($is_clearance){
            $query->where('is_clearance', $is_clearance);
        }

        if($pre_out_date_start && $pre_out_date_end){
            $query->whereBetween('pre_out_date', [$pre_out_date_start, $pre_out_date_end]);
        }

        $total = $query->count('id');
        $orders = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();
        
        $list = $orders->map(function($order) {
//            $load_pkgs = $order->big_pkgs - $order->load_pkgs_surplus;
//            $load_weight = $order->big_pkgs - $order->surplus_weight;

            return [
                'id' => $order->id,
                'customer_name' => $order->customer->name ?? '',
                'customer_sn' => $order->customer->sn ?? '',
                'customer_type' => $order->customer->customer_type->name ?? '',
                'sn' => $order->sn,
                'storage_time' => $order->storage_time,
                'pre_out_date' => $order->pre_out_date,
                'des_country' => $order->destination,
                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
                'pkgs_progress' => $order->load_pkgs . '/' . $order->big_pkgs,
                'weight_progress' => $order->load_weight . '/' . $order->storage_weight,
                'load_pkgs_surplus' => $order->load_pkgs_surplus,
                'surplus_weight' => $order->surplus_weight,
            ];
        });

        return $this->success(['list' => $list, 'total' => $total]);

    }

    //配载入仓单
    public function loading(Request $request) {
        $params = $request->all();
        $validator = Validator::make($params, [
            'id' => 'required|integer',
            'nums' => 'required|integer|min:1',
            'weight' => 'required|numeric|min:0.01',
            'type' => 'required|integer|in:1,2,3',
            'task_id' => 'required|integer',
        ], [
            'id.required' => '请选择入仓单',
            'nums.required' => '请输入运输件数',
            'weight.required' => '请输入重量',
            'weight.min' => '重量必须大于0',
            'type.required' => '请选择运输类型',
            'type.in' => '请选择车辆类型',
            'task_id.required' => '请选择配载车辆'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $task = DispatchTaskModel::find($params['task_id']);
        if(!$task){
            return $this->error('任务不存在');
        }

        if($task->type != $params['type']) {
            return $this->error('任务类型与车辆类型不匹配');
        }

        $order = OrderModel::find($params['id']);
        if(!$order){
            return $this->error('入仓单不存在');
        }

//        if($order->load_pkgs_surplus < $params['nums']) {
//            return $this->error('入仓单大包数量不足');
//        }
//
//
//        if($order->surplus_weight < $params['weight']) {
//            return $this->error('入仓单重量不足');
//        }

        try{
            DB::transaction(function () use ($task, $order, $params) {
                $order->load_pkgs = DB::raw("load_pkgs + {$params['nums']}");
                $order->load_weight = DB::raw("load_weight + {$params['weight']}");
                $order->car_number = $task->car->car_number ?? '';
                $order->save();

                $load_list = new DispatchLoadListModel();
                $load_list->dispatch_task_id = $task->id;
                $load_list->order_id = $order->id;
                $load_list->big_pkgs = $params['nums'];
                $load_list->weight = $params['weight'];
                $load_list->hk_unload_id = $params['hk_unload_id'] ?? 0;
                $load_list->save();
            });
        } catch(\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();

    }

    //撤出
    public function remove(Request $request, $id) {
        $task = DispatchTaskModel::find($id);
        if(!$task){
            return $this->error('任务不存在');
        }

        $load_id = $request->input('load_id', 0);

        $load_order = DispatchLoadListModel::where('id', $load_id)->first();

        if(!$load_order) {
            return $this->success();
        }

        DB::transaction(function () use ($load_order) {
            $order = OrderModel::find($load_order->order_id);
            if(!$order) {
                $load_order->delete();
            }else{
                $load_pkgs = $order->load_pkgs - $load_order->big_pkgs;
                $order->load_pkgs = $load_pkgs;
                $order->load_weight = DB::raw("load_weight - {$load_order->weight}");

                if($load_pkgs >= $order->big_pkgs){
                    $order->is_load  = 2;
                }else{
                    $order->is_load  = 1;
                }
                $order->save();

                $load_order->delete();
            }

        });

        return $this->success();
    }

    /**
     * Notes:运输信息
     * User: xiangzi
     * Date: 2024/10/10
     * Time: 17:26
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function transport_record(Request $request)
    {
        $id = $request->input('id', 0);

        $model = DispatchTaskModel::query()
            ->with([
                'load_warehouse', 'unload_warehouse', 'driver', 'hk_driver', 'car', 'feng', 'load_list'
            ])->find($id);

        if (!$model) {
            return $this->error('数据不存在');
        }

//        $location_record = DispatchTaskLocationModel::where('task_id', $id)->orderBy('id', 'desc')->first();
        $location_info = [
            'location' => '',
            'time' => ''
        ];
//        if ($location_record) {
//            $location_info['location'] = $location_record->location;
//            $location_info['time'] = $location_record->created_at->toDateTimeString();
//        }

        $transport_info = [];

        $record = DispatchTaskRecordModel::with('driver')->where('task_id', $id)->orderBy('id', 'asc')->get();

        foreach ($record as $item) {
            $driver_name = $item->driver->name ?? '';

            $time = $item->time;
            if($item->location){
                $time .= '【' . $item->location . '】';
            }
            $transport_info[] = [
                'time' => $time,
                'desc' => $item->desc . '【' . $driver_name . '】',
            ];
        }

        $return['transport_info'] = $transport_info;
        $return['location_info'] = $location_info;

        return $this->success($return);
    }


    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = DispatchTaskModel::with(['car', 'loads', 'unloads', 'driver', 'hk_driver', 'feng', 'agent', 'type', 'load_list']);
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            //车牌号
            $car_number = $item->car->car_number ?? '';

            //装车地
            $load_warehouse_ids = $item->loads->map(function ($item2) {
                return $item2->warehouse_id;
            });

            $load_warehouse_name = WarehouseModel::whereIn('id', $load_warehouse_ids)->pluck('name')->toArray();

            //卸货地
            $unload_warehouse_ids = $item->unloads->map(function ($item2) {
                return $item2->warehouse_id;
            });

            $unload_warehouse_name = UnloadModel::whereIn('id', $unload_warehouse_ids)->pluck('name')->toArray();

            $driver_info = $hk_driver_info = '';
            if($item->driver){
                $name = $item->driver->name ?? '';
                $mobile = $item->driver->mobile ?? '';
                $hk_mobile = $item->driver->mobile ?? '';
                $car_number = $item->car->car_number ?? '';

                $driver_info = '姓名：' . $name . ' 电话：' . $mobile . ' 香港电话：' . $hk_mobile . ' 身份证：' . $car_number;
            }

            if($item->hk_driver){
                $name = $item->hk_driver->name ?? '';
                $mobile = $item->hk_driver->mobile ?? '';
                $hk_mobile = $item->hk_driver->mobile ?? '';
                $id_card = $item->hk_driver->id_number ?? '';
                $card_number = $item->hk_driver->card_number?? '';

                $hk_driver_info = '姓名：' . $name . ' 电话：' . $mobile . ' 香港电话：' . $hk_mobile . ' 卡号：' . $id_card . ' 身份证：' . $card_number;
            }

            return [
                'car_type' => $item->type->name ?? '',
                'driver_info' => $driver_info,
                'hk_driver_info' => $hk_driver_info,
                'agent_name' => $item->agent->name ?? '',
                'car_number' => $car_number,
                'load_warehouse' => implode(',', $load_warehouse_name),
                'unload_warehouse_name' => implode(',', $unload_warehouse_name),
                'feng_name' => $item->feng->name ?? '',
                'load_date' => $item->load_date,
                'big_pkgs' => $item->load_list->sum('big_pkgs'), //大包数量
                'weight' => $item->load_list->sum('weight'), //
            ];
        });

        $file_name = '装车表-'.date('Ymd').'.xlsx';

        return Excel::download(new TaskExport($list), $file_name);
    }

    /**
     * 导出装车表
     * @param Request $request
     */
    public function load_export(Request $request)
    {
        $id = $request->input('id', '');

        $task = DispatchTaskModel::with(['load_list', 'driver', 'hk_driver'])->find($id);

        $car_number = $task->car->car_number ?? '';

        $driver = $task->driver;
        $hk_driver = $task->hk_driver;

        $driver_info = $hk_driver_info = '';
        if($driver){
            $type = '大陆司机';
            $driver_info .= $type . '：' . $driver->name;
            $driver_info .= ' 电话：' . $driver->mobile;
            $driver_info .= ' 身份证号：' . $driver->id_number;
        }

        if($hk_driver){
            $type = '港车司机';
            $hk_driver_info .= $type . '：' . $hk_driver->name;
            $hk_driver_info .= ' 卡号：' . $hk_driver->card_number;
            $hk_driver_info .= ' 电话：' . $hk_driver->mobile;

        }

        $car_type = DictionaryModel::find($task->car->type_id)->name ?? '';

        //装车地
        $load_warehouse_ids = $task->loads->map(function ($item2) {
            return $item2->warehouse_id;
        });

        $load_warehouse_name = WarehouseModel::whereIn('id', $load_warehouse_ids)->pluck('name')->toArray();

        //卸货地
        $unload_warehouse_ids = $task->unloads->map(function ($item2) {
            return $item2->warehouse_id;
        });

        $unload_warehouse_name = UnloadModel::whereIn('id', $unload_warehouse_ids)->pluck('name')->toArray();

        $nerv = [
            'car_number' => $car_number,
            'car_type' => $car_type,
            'driver' => $driver_info,
            'hk_driver' => $hk_driver_info,
            'feng' => $task->feng->name ?? '',
            'big_pkgs' => $task->load_list->sum('big_pkgs'),
//            'weight' => $task->load_list->sum('weight'),
            'load_warehouse' => implode(',', $load_warehouse_name),
            'unload_warehouse' => implode(',', $unload_warehouse_name),
        ];

        $data = [$nerv];

        $list = $task->load_list->map(function($item) {
            //装货进度
            $order_big_pkgs = $item->order->big_pkgs ?? 0;
            $order_load_surplus = $item->order->load_pkgs_surplus ?? 0;
            $progress =  $order_big_pkgs - $order_load_surplus . "/{$order_big_pkgs}";

            //包装
            $packages_name = DictionaryModel::whereIn('id', explode(',', $item->packages))
                ->pluck('name')->implode('+');

            return [
                'customer_name' => $item->order->customer->name ?? '',
                'order_sn' => $item->order->sn ?? '',
                'destination' => $item->order->destination ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->order->goods_attr ?? ''] ?? '',
                'load_nums' => $item->big_pkgs,  //装载大包件数
                'weight' => $item->weight,
                'progress' =>  $progress,
                'packages_name' => $packages_name,
            ];
        });

        $list = $list->toArray();
        $data = array_merge($data, $list);

        $file_name = $car_number .'-装车表-'.date('Ymd').'.xlsx';

        return Excel::download(new TaskLoadExport(collect($data)), $file_name);
    }


    public function declare_list(Request $request)
    {
        $id = $request->input('id', '');
        $task = DispatchTaskModel::with(['load_list'])->find($id);


        $list = $task->load_list->map(function($item) {
            $clearance_list = [];
            if($item->order->clearance_list){
                $clearance_list = explode(',', $item->order->clearance_list);
            }
            return [
                'order_sn' => $item->order->sn ?? '',
                'clearance_list' => $clearance_list,
            ];
        });

        return $this->success($list);
    }


    public function import(Request $request)
    {
        $file = $request->file('file');
        $id = $request->input('id', '');

        $task = DispatchTaskModel::find($id);
        if(!$task){
            return $this->error('任务不存在');
        }

        $import = new TaskImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        $car_number = $task->car->car_number ?? '';

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $order = OrderModel::where('sn', $line['order_sn'])->first();

                $load_list = new DispatchLoadListModel();
                $load_list->dispatch_task_id = $task->id;
                $load_list->big_pkgs = $line['nums'];
                $load_list->weight = $line['weight'];

                //子单
                if($line['nums'] < $order->big_pkgs){
                    $new_order = $order->replicate();
                    $order->children_nums += 1;

                    $new_order->sn = $order->sn . '_' . DispatchLoadListModel::CHILDREN_SN[$order->children_nums];
                    $new_order->is_child = 1;
                    $new_order->father_order_id = $order->id;
                    $new_order->status = OrderModel::STATUS_OUTSTOCK;
                    $new_order->car_number = $task->car->car_number ?? '';
                    $new_order->load_pkgs = $line['nums'];
                    $new_order->load_weight = $line['weight'];
                    $new_order->big_pkgs = $line['nums'];
                    $new_order->storage_weight = $line['weight'];
                    $new_order->out_time = date('Y-m-d H:i:s');
                    $new_order->is_load = 2;
                    $new_order->save();

                    $this->node_log($request, $new_order->id, '出库', date('Y-m-d H:i:s'));

                    $load_list->order_id = $new_order->id;
                }else{
                    $load_list->order_id = $order->id;

                    $this->node_log($request, $order->id, '出库', date('Y-m-d H:i:s'));
                }

                $load_list->save();


                $load_pkgs = $order->load_pkgs + $line['nums'];
                $load_weight = $order->load_weight + $line['weight'];
                $order->load_pkgs = $load_pkgs;
                $order->load_weight = $load_weight;
                $order->status = OrderModel::STATUS_OUTSTOCK;
                $order->outstock_time = date('Y-m-d H:i:s');
                $order->out_time = date('Y-m-d H:i:s');
                $order->car_number = $car_number;

                if($load_pkgs >= $order->big_pkgs){
                    $order->is_load  = 2;
                }else{
                    $order->is_load  = 1;
                }
                $order->save();

                $task->load_form = 2;
                $task->save();

            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

    /**
     * 出库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function out(Request $request)
    {
        $ids = $request->input('ids', []);
        $time = $request->input('time', '');

        if(!$time){
            return $this->error('请选择时间');
        }

        $tasks = DispatchTaskModel::find($ids);

        if(!$tasks){
            return $this->error('任务不存在');
        }

        DB::beginTransaction();
        try {
            $status = $tasks->pluck('node_status')->unique();
            if($status->count() > 1){
                return $this->error('节点状态不一致');
            }
            if($status->first()){
                return $this->error('节点状态已更新');
            }

            foreach ($tasks as $task){
                $task->out_time = $time;
                $task->node_status = DispatchTaskModel::NODE_STATUS_OUT;
                $task->save();
            }

            $order_ids = DispatchLoadListModel::whereIn('dispatch_task_id', $ids)->pluck('order_id');

            OrderModel::whereIn('id', $order_ids)->update([
                'status' => OrderModel::STATUS_OUTSTOCK,
                'out_time' => $time,
            ]);

            foreach ($order_ids as $order_id){
                $this->node_log($request, $order_id, '出库', $time);
            }

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * 报关
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function declare(Request $request)
    {
        $ids = $request->input('ids', []);
        $time = $request->input('time', '');

        if(!$time){
            return $this->error('请选择时间');
        }


        $tasks = DispatchTaskModel::find($ids);

        if(!$tasks){
            return $this->error('任务不存在');
        }

//        $status = $tasks->pluck('node_status')->unique();
//        if($status->count() > 1){
//            return $this->error('节点状态不一致');
//        }
//        if($status->first() != DispatchTaskModel::NODE_STATUS_OUT){
//            return $this->error('节点状态错误');
//        }

        $order_ids = DispatchLoadListModel::whereIn('dispatch_task_id', $ids)->pluck('order_id');

       $orders_status = OrderModel::whereIn('id', $order_ids)->pluck('status')->unique();
       if($orders_status->count() > 1){
            return $this->error('入仓单状态不一致');
        }
       if($orders_status->first() != OrderModel::STATUS_OUTSTOCK){
            return $this->error('入仓单状态必须为出库状态');
        }

        DB::beginTransaction();
        try {

            foreach ($tasks as $task){
                $task->declare_time = $time;
                $task->node_status = DispatchTaskModel::NODE_STATUS_DECLARE;
                $task->save();
            }



            OrderModel::whereIn('id', $order_ids)->update([
                'status' => OrderModel::STATUS_DECLARE,
                'declare_time' => $time,
            ]);

            foreach ($order_ids as $order_id){
                $this->node_log($request, $order_id, '报关', $time);
            }

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * 查验
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function check(Request $request)
    {
        $ids = $request->input('ids', []);
        $time = $request->input('time', '');

        if(!$time){
            return $this->error('请选择时间');
        }

        $tasks = DispatchTaskModel::find($ids);

        if(!$tasks){
            return $this->error('任务不存在');
        }

        $status = $tasks->pluck('node_status')->unique();
        if($status->count() > 1){
            return $this->error('节点状态不一致');
        }
        if($status->first() != DispatchTaskModel::NODE_STATUS_DECLARE){
            return $this->error('节点状态错误');
        }

        DB::beginTransaction();
        try {
            foreach ($tasks as $task){
                $task->check_time = $time;
                $task->node_status = DispatchTaskModel::NODE_STATUS_CHECK;
                $task->save();
            }

            $order_ids = DispatchLoadListModel::whereIn('dispatch_task_id', $ids)->pluck('order_id');

            OrderModel::whereIn('id', $order_ids)->update([
                'status' => OrderModel::STATUS_CHECK,
                'check_time' => $time,
                'is_exception' => 1,
            ]);

            foreach ($order_ids as $order_id){
                $this->node_log($request, $order_id, '查验', $time);
            }

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * 放行
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function pass(Request $request)
    {
        $ids = $request->input('ids', []);
        $time = $request->input('time', '');

        if(!$time){
            return $this->error('请选择时间');
        }


        $tasks = DispatchTaskModel::find($ids);

        if(!$tasks){
            return $this->error('任务不存在');
        }

        $status = $tasks->pluck('node_status')->unique();
        if($status->count() > 1){
            return $this->error('节点状态不一致');
        }
        if($status->first() != DispatchTaskModel::NODE_STATUS_DECLARE && $status->first() != DispatchTaskModel::NODE_STATUS_CHECK){
            return $this->error('节点状态错误');
        }


        DB::beginTransaction();
        try {
            foreach ($tasks as $task){
                if($time && $task->declare_time > $time){
                    return $this->error('放行时间不能小于报关时间');
                }

                $task->pass_time = $time;
                $task->node_status = DispatchTaskModel::NODE_STATUS_PASS;
                $task->save();
            }

            $order_ids = DispatchLoadListModel::whereIn('dispatch_task_id', $ids)->pluck('order_id');

            OrderModel::whereIn('id', $order_ids)->update([
                'status' => OrderModel::STATUS_PASS,
                'pass_time' => $time,
            ]);

            foreach ($order_ids as $order_id){
                $this->node_log($request, $order_id, '放行', $time);
            }

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


    public function exception(Request $request)
    {
        $auth = $request->get('auth');
        $ids = $request->input('ids', []);
        $name = $request->input('name', '');
        $time = $request->input('time', '');

        if(!$name){
            return $this->error('请填写异常名称');
        }

        $tasks = DispatchTaskModel::find($ids);

        if(!$tasks){
            return $this->error('任务不存在');
        }

        DB::beginTransaction();
        try {
            foreach ($tasks as $task){
                $exception = new ExceptionModel();
                $exception->task_id = $task->id;
                $exception->name = $name;
                $exception->time = $time;
                $exception->created_admin_id = $auth->id;
                $exception->save();
            }

            $order_ids = DispatchLoadListModel::whereIn('dispatch_task_id', $ids)->pluck('order_id');

            OrderModel::whereIn('id', $order_ids)->update([
                'is_exception' => 1,
            ]);

            foreach ($order_ids as $order_id){
                $this->node_log($request, $order_id, '异常（'.$name.'）', $time);
            }

            DB::commit();

        } catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


    /**
     * 节点日志
     * @param $request
     * @param $order_id
     * @param $name
     * @param $time
     * @return void
     */
    public function node_log($request, $order_id, $name, $time)
    {
        $auth = $request->get('auth');

        $log = new OrderNodeLogModel();
        $log->order_id = $order_id;
        $log->name = $name;
        $log->time = $time;
        $log->type = 2;
        $log->url = $request->url();
        $log->created_admin_id = $auth->id;
        $log->save();

    }


}
